package com.linwen.javase.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName _05LockWaitNotify
 * @Description
 * @Author lin
 * @Date 2022/4/19 下午11:28
 * @Version V1.0
 */
public class _05LockWaitNotifyThread {
    public static void main(String[] args) {
        LockWaitNotify lockWaitNotify = new LockWaitNotify();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    lockWaitNotify.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"AAA").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    lockWaitNotify.decr() ;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"BBB").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    lockWaitNotify.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"CCC").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    lockWaitNotify.decr() ;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"DDD").start();
    }
}
class LockWaitNotify{
    private int num = 0;
    private final Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void incr() throws InterruptedException {
        lock.lock();
        try {
            while (num!=0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+" "+num++);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public void decr() throws InterruptedException {
        lock.lock();
        try {
            while (num==0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+" "+num--);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}